import vue from '@vitejs/plugin-vue'
import postcssNested from 'postcss-nested'
import { defineConfig } from 'vite'
import dts from 'vite-plugin-dts'

export default defineConfig({
  css: {
    postcss: {
      plugins: [postcssNested({ preserveEmpty: true })]
    }
  },
  plugins: [
    vue(),
    dts({
      tsconfigPath: './tsconfig.lib.json',
      exclude: ['**/__tests__/**'],
      outDir: ['es', 'lib']
    }),
    {
      name: 'vite:import-css',
      apply: 'build',
      enforce: 'post',
      renderChunk(code, chunk) {
        // 判断是不是组件入口js
        if (
          !chunk.isEntry &&
          chunk.type === 'chunk' &&
          /\/index.(js)$/i.test(chunk.fileName)
        ) {
          const strictStr = "'use strict';"

          if (code.includes(strictStr)) {
            code = code.replace("'use strict';", '')
            return `${strictStr}\nimport './style.css';\n${code}`
          }
          return `import './style.css';\n${code}`
        }
      }
    }
  ],
  build: {
    lib: {
      entry: 'src/index.ts'
    },
    emptyOutDir: true,
    minify: false,
    sourcemap: false,
    cssCodeSplit: true,
    rollupOptions: {
      external: ['vue'],
      output: [
        {
          format: 'es',
          entryFileNames: '[name].js',
          preserveModules: true,
          preserveModulesRoot: './src',
          dir: 'es',
          assetFileNames: assetInfo => {
            if (
              assetInfo.type === 'asset' &&
              /\.(css)/i.test(assetInfo.name || '')
            ) {
              const str = (assetInfo.name || 'style.').split('.')[0]
              return `${str}.css`
            } else {
              return 'assets/[name].[ext]'
            }
          }
        },
        {
          format: 'cjs',
          entryFileNames: '[name].js',
          preserveModules: true,
          preserveModulesRoot: './src',
          dir: 'lib',
          assetFileNames: assetInfo => {
            if (
              assetInfo.type === 'asset' &&
              /\.(css)/i.test(assetInfo.name || '')
            ) {
              const str = (assetInfo.name || 'style.').split('.')[0]
              return `${str}.css`
            } else {
              return 'assets/[name].[ext]'
            }
          }
        }
      ]
    }
  }
})
